package com.macro.mall.controller;

import com.macro.mall.common.config.XhsApiConfig;
import com.macro.mall.common.exception.XhsApiException;
import com.macro.mall.service.XhsLoginService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

@Controller
@Api(tags = "XhsLoginController")
@Tag(name = "XhsLoginController", description = "华帝小红书小程序登录")
@RequestMapping("/huadi")
public class XhsLoginController {


    @Resource
    private XhsLoginService xhsLoginService;


    @Resource
    private XhsApiConfig xhsApiConfig;


    // 从配置文件中读取参数（建议放在application.yml/properties）
    @Value("${xhs.app-id}")
    private String APP_ID;

    @Value("${xhs.access-token}")
    private String ACCESS_TOKEN;

    @Resource
    private  OkHttpClient okHttpClient;


    @GetMapping("/xhs/login")
    public XhsResponse login(@RequestParam String code) {
        // 构建请求URL
        HttpUrl url = HttpUrl.parse(xhsApiConfig.getBaseUrl() + "/api/rmp/session").newBuilder()
                .addQueryParameter("app_id", APP_ID)
                .addQueryParameter("access_token", ACCESS_TOKEN)
                .addQueryParameter("code", code)
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                return handleErrorResponse(response);
            }

            // 解析响应
            ResponseBody body = response.body();
            if (body != null) {
                // 实际实现需要完整的JSON解析
                // 这里使用简化示例，建议使用Jackson完整解析
                String responseBody = body.string();
                return parseResponse(responseBody);
            }
            return new XhsResponse(false, "Empty response", -1, null);
        } catch (IOException e) {
            return new XhsResponse(false, "API request failed: " + e.getMessage(), -500, null);
        }
    }

    // 解析响应（需要根据实际响应结构调整）
    private XhsResponse parseResponse(String responseBody) {
        // 实际实现应使用JSON解析库（如Jackson）
        // 这里演示基本结构，建议创建完整的DTO类
        if (responseBody.contains("\"code\":0")) {
            return new XhsResponse(true, "success", 0, new XhsData("openid_demo", "session_key_demo"));
        }
        return new XhsResponse(false, "Unknown error", -1, null);
    }

    private XhsResponse handleErrorResponse(Response response) {
        return new XhsResponse(false,
                "API Error: " + response.message(),
                response.code(),
                null);
    }

    // 响应DTO
    @Data
    static class XhsResponse {
        private Boolean success;
        private String msg;
        private Integer code;
        private XhsData data;

        public XhsResponse(boolean success, String msg, Integer code, XhsData data) {
            this.success = success;
            this.msg = msg;
            this.code = code;
            this.data = data;
        }
    }

    @Data
    static class XhsData {
        private String openid;
        private String session_key;

        public XhsData(String openid, String session_key) {
            this.openid = openid;
            this.session_key = session_key;
        }
    }














    @GetMapping("/token")
    public String getToken() throws XhsApiException {
        return xhsLoginService.getValidToken();
    }




}
